package jerry.cn.polybasiccompress.PictureCacheALG;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

class Engine {
    private InputStreamResource inputStreamResource;
    private File TargetDir;
    private int srcW;
    private int srcH;
    private boolean AlphaAisle = false;

    Engine(InputStreamResource inputStreamResource, File taegetDir, boolean alphaAisle) throws IOException {
        this.inputStreamResource = inputStreamResource;
        this.TargetDir = taegetDir;
        this.AlphaAisle = alphaAisle;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = 1;

        BitmapFactory.decodeStream(inputStreamResource.open(), null, options);
        this.srcW = options.outWidth;
        this.srcW = options.outHeight;
    }

    private int computeSize() {
        srcW = srcW % 2 == 1 ? srcW + 1 : srcW;
        srcH = srcH % 2 == 1 ? srcH + 1 : srcH;

        int longSide = Math.max(srcW, srcH);
        int shortSide = Math.min(srcW, srcH);

        float scale = ((float) shortSide / longSide);
        if (scale <= 1 && scale > 0.5625) {
            if (longSide < 1664) {
                return 1;
            } else if (longSide < 4990) {
                return 2;
            } else if (longSide > 4990 && longSide < 10240) {
                return 4;
            } else {
                return longSide / 1280 == 0 ? 1 : longSide / 1280;
            }
        } else if (scale <= 0.5625 && scale > 0.5) {
            return longSide / 1280 == 0 ? 1 : longSide / 1280;
        } else {
            return (int) Math.ceil(longSide / (1280.0 / scale));
        }
    }

    private Bitmap rotatingImage(Bitmap bitmap, int angle) {
        Matrix matrix = new Matrix();

        matrix.postRotate(angle);

        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }


    File compress() throws IOException {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = computeSize();

        Bitmap tagBitmap = BitmapFactory.decodeStream(inputStreamResource.open(), null, options);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        if (CheckAll.SINGLE.isJPG(inputStreamResource.open())) {
            tagBitmap = rotatingImage(tagBitmap, CheckAll.SINGLE.getOrientation(inputStreamResource.open()));
        }
        tagBitmap.compress(AlphaAisle ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 60, stream);
        tagBitmap.recycle();

        FileOutputStream fos = new FileOutputStream(TargetDir);
        fos.write(stream.toByteArray());
        fos.flush();
        fos.close();
        stream.close();

        return TargetDir;
    }
}
